package com.base.controller.api;

import com.base.comm.CommUrls;
import com.base.controller.Parameters;
import com.base.helper.ApiinfoesHelper;
import com.base.helper.VosHelper;
import com.base.po.acess.AcessToken;
import com.base.po.acess.TokenUtils;
import com.base.po.param.NetState;
import com.base.po.param.VosModelList;
import com.base.po.requestParam.SubscribersParam;
import com.base.po.result.UserInfo;
import com.base.po.sqlparam.CallbackinfoesExamplePage;
import com.base.po.voip.*;
import com.base.po.voip.CallbackinfoesExample.Criteria;
import com.base.po.voip_sdk.SubscribersResponse;
import com.base.po.voip_sdk.UserInfoResponse;
import com.base.result.ResponseResult;
import com.base.result.ResponseResultUtils;
import com.base.self.service.CommissionService;
import com.base.service.*;
import com.base.utils.GsonUtil;
import com.base.utils.PasswordUtils;
import com.base.utils.Produce;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户信息控制器
 *
 * @author Administrator
 *
 */
@Slf4j
@Controller
@RequestMapping("/userInfo")
@Api(tags = "用户信息")
public class UserInfoController extends IgRewardsController{
	@Autowired
	private AboutsService aboutsService; // 联系我们Service
	@Autowired
	private ApiinfoesService apiinfoesService;
	@Autowired
	private SubscribersService subscribersService;
	@Autowired
	private UsersService usersService;
	@Autowired
	private UserpaysService userpaysService;
	@Autowired
	private UserAuthInfoService userAuthInfoService;
	@Autowired
	private CallbackinfoesService callbackinfoesService;
	@Autowired
	private TaskRewardService taskRewardService; // 任务信息
	@Autowired
	private TaskReachService taskReachService; // 领取信息
	@Autowired
	private RewardsService rewardsService;
    @Autowired
    private JpushIdService jpushIdService;
    @Autowired
	private InviteCodeService inviteCodeService;
    @Autowired
	private CommissionService commissionService;

	// 个人信息
	@CrossOrigin
	@RequestMapping(value = "/getBlance", method = RequestMethod.POST)
	public @ResponseBody NetState getBlance(HttpServletRequest request, String registration_id) throws Exception {
		log.warn("请求/getBlance registration_id {}", registration_id);
		NetState netState = new NetState();
		String AuthorizationToken = request.getHeader("SDB-Authorization");
		AcessToken acessToken = null;
		if (AuthorizationToken != null && !AuthorizationToken.equals("")){
			acessToken = TokenUtils.getAcessToken(AuthorizationToken);
		}
		if (acessToken == null) {
			netState.setData("数据签名错误");
			netState.setErrorCode(NetState.SIGN_ERROR);
		} else {
			String Mobile = acessToken.getMobile();
			String ParentId = acessToken.getParentid();
			// 验证参数
			if (Mobile == null || Mobile.equals("") || ParentId == null || ParentId.equals("")) {
				netState.setErrorCode(NetState.PARAMS_ERROR);
				netState.setData("客户端参数错误");
			} else {
				// 查看重复注册
				List<Subscribers> allSub = subscribersService.selectBySub(Mobile, ParentId);
				if (allSub != null && allSub.size() > 1){
					for (Subscribers s : allSub){
						if (s.getShareper() == null || s.getShareper().equals("")){
							subscribersService.deleteByPrimaryKey(s.getId());
						}
					}
				}

//				SubscribersExample subscribersExample = new SubscribersExample();
//				subscribersExample.getOredCriteria().add(subscribersExample.createCriteria().andMobileEqualTo(Mobile)
//						.andParentidEqualTo(ParentId).andDatastatusEqualTo(true));
//				List<Subscribers> subscribers = subscribersService.selectByExample(subscribersExample);
				List<Subscribers> subscribers = subscribersService.selectBySub(Mobile, ParentId);
				if (subscribers != null && subscribers.size() > 0) {
					Subscribers us = subscribers.get(0);
					us.setCypher(PasswordUtils.decodePWD(us.getPassword()));

					// 绑定极光推送推送id
					try{
						if (registration_id != null){
							List<JpushId> jpushId = jpushIdService.selectByUserID(us.getId());
							if (jpushId == null || jpushId.equals("")){
								jpushIdService.insertSelective(new JpushId(us.getId(), registration_id));
							}
						}
					}catch (Exception e){
						System.out.println("推送id更新失败");
					}

					// 绑定用户邀请码
					List<InviteCode> inviteCode = inviteCodeService.selectByUserID(us.getId());
					if (inviteCode != null && inviteCode.size() > 0){
						us.setInvitecode(inviteCode.get(0).getCode());
					}else{
						String code = us.getId().substring(us.getId().length() - 6);
						us.setInvitecode(code);
						inviteCodeService.insertSelective(new InviteCode(us.getId(), code));
					}

					UsersExample usersExample = new UsersExample();
					usersExample.getOredCriteria()
							.add(usersExample.createCriteria().andIdEqualTo(ParentId).andDatastatusEqualTo(true));
					List<Users> agents = usersService.selectByExample(usersExample);
					if (agents != null && agents.size() == 1) {
						Users agent = agents.get(0);

						if (agent.getIsmember() == 1 && !agent.equals("6322af2691ba4c8884568c94cc806718")){
							int fans = rewardsService.selectByCount(us.getId());
							// 基本会员刚刚注册 更新会员开始时间
							if (us.getMembertime() == null){
								us.setMembertime(Produce.getNowDate());
								subscribersService.updateByPrimaryKeySelective(us);
							}
							// 基本会员 粉丝到达升级数量 升级为自定义的会员
							if (us.getMember() == 1 && fans > agent.getUpgrade2()){
								us.setMember(2);
								us.setMembertime(Produce.getNowDate());
								subscribersService.updateByPrimaryKeySelective(us);
							}
							// 基本会员 45天没升级 脱离团队
							if (us.getMember() == 1 && Produce.differentDays(us.getMembertime(), Produce.getNowDate()) > 45 && fans < agent.getUpgrade2()){
								us.setMember(0);
								us.setMembertime(Produce.getNowDate());
								subscribersService.updateByPrimaryKeySelective(us);
							}
						}

						if (us.getShopEnddate().contains("CST")) {
							SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
							try {
								Date date = sdf1.parse(us.getShopEnddate());
								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
								String sDate = sdf.format(date);
								System.out.println(sDate);
								us.setShopEnddate(sDate);
							} catch (ParseException e) {
								e.printStackTrace();
							}
						}

						String w = "";
						String time = "";
						String result = VosHelper
								.GetVosAccount("{accounts:['" + agent.getAgentprefix() + us.getMobile() + "']}");
						VosModelList v1 = GsonUtil.getObject(result, VosModelList.class);
						System.out.println(JSONObject.fromObject(v1));
						if (v1.retCode == 0) {
							if (v1.infoCustomers.length > 0) {
								DecimalFormat df = new DecimalFormat("#0.00");
								if (us.getType() == 7) {
									if (Produce.differentDays(new Date(), new Date(v1.infoCustomers[0].getValidTime())) < 0){
										if (agent.getId().equals("478f572854384205972fae478a81948c")){
											BigDecimal money = v1.infoCustomers[0].getMoney().multiply(new BigDecimal(-1));
											// 话费清零
											String payinfo = VosHelper
													.PayVosAccount("{\"ownerName\":\"" + agent.getAgentprefix()
															+ us.getMobile() + "\",\"ownerType\":\"2\",\"money\":\""
															+ money + "\",\"memo\":\"" + agent.getUsername()
															+ "到期清零"+ money  + "元\"}");
											// 再次查询用户数据
											result = VosHelper
													.GetVosAccount("{accounts:['" + agent.getAgentprefix() + us.getMobile() + "']}");
											v1 = GsonUtil.getObject(result, VosModelList.class);
										}else if (agent.getId().equals("d093179851af43dfbb1bc6639334b109") && us.getIsyearcard() == 1){
											us.setIsyearcard(2);
											subscribersService.updateByPrimaryKeySelective(us);
										}
									}
									w = df.format(v1.infoCustomers[0].getMoney());
//									w = v1.infoCustomers[0].getMoney().toString();
									time = new SimpleDateFormat("yyyy-MM-dd")
											.format(new Date(v1.infoCustomers[0].getValidTime()));
								} else {
									// vos
									int day = Produce.differentDays(new Date(v1.infoCustomers[0].getValidTime()),
											Produce.getNowDate());
									if (us.getType() == 1) {
										w = "" + day + "天/";
									}
									if (us.getType() == 2) {
										w = "" + day + "天/";
									}
									if (us.getType() == 3) {
										w = "" + day + "天/";
									}
									w = df.format(v1.infoCustomers[0].getMoney());
								}
							} else {
								w = "0";
								time = "1970-01-01";
							}
						} else {
							w = "0";
							time = "1970-01-01";
						}
						String[] a = us.getShopEnddate().split(",");
						agent.setIsauth(a.length > 0);
						us.setUsers(agent);
						if (agent.getId().equals("b82d635e95be4bd983acef092118785b")||agent.getId().equals("a6b818fa0a4b4b7c97da4bff24ff1d6a")){
							try {
							    us.setLevelAll(rewardsService.countByLevel1(us.getId()) + rewardsService.countByLevel2(us.getId()) + rewardsService.countByLevel3(us.getId()));
						    }catch (Exception e){
								us.setLevelAll(0);
							}
						}
						try{
							us.setBankaccount(userpaysService.selectByUserID(us.getId(), true).getBankno());
							us.setRealname(userpaysService.selectByUserID(us.getId(), true).getBankrealname());
						}catch (Exception e){
							us.setBankaccount("");
							us.setRealname("");
						}
						try{
							us.setAliname(userpaysService.selectByUserID(us.getId(), true).getName());
						}catch (Exception e){
							us.setAliname("");
						}
						UserInfo info = new UserInfo();
						info.AndroidVer = agent.getAndroidversion();
						info.AndroidPa = agent.getAndroidpath();
						info.IOSVer = agent.getIosversion();
						info.IOSPa = agent.getIospath();
						info.IsAuth = agent.getIsauth();
						info.Money = w;
						info.Time = time;
						info.Info = us;
						if (!time.equals("")) {
							us.setEndtime(new SimpleDateFormat("yyyy-MM-dd").parse(time));
						}
						subscribersService.updateByPrimaryKeySelective(us);
						netState.setErrorCode(NetState.SUCCESS_CONN);
						netState.setJson(info);
						netState.setData("获取用户信息成功");
						/**
						 *  获取客服的信息
						 */
						Abouts abouts=aboutsService.selectByUserID(ParentId);
						netState.setOtherJson(abouts);
						/**
						 * 每日任务-登录开始
						 */
						// 判断用户是否领取任务
						List<TaskReach> tr = taskReachService.selectByTaskReach(us.getId(), us.getParentid(),
								new SimpleDateFormat("yyyy-MM-dd").format(Parameters.getNowDate()), 1);
						if (tr != null && tr.size() > 0 && tr.get(0).getReceivestatus() == 1 && tr.get(0).getCompletestatus() == 0)
							// 写入用户登录信息
							taskRewardService.insertSelective(
									new TaskReward(us.getParentid(), us.getId(), Produce.getNowDate(), 1));
						/**
						 * 每日任务-登录结束
						 */
					} else {
						netState.setErrorCode(NetState.ACCOUNT_ERROR);
						netState.setData("获取用户信息信息失败");
					}

				} else {
					netState.setErrorCode(NetState.ACCOUNT_ERROR);
					netState.setData("用户不存在");
				}
			}
		}
//		Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "查询用户信息");
//		apiinfoesService.insert(
//				ApiinfoesHelper.setApiinfoes(apiinfoes, AuthorizationToken, GsonUtil.createJsonString(netState)));
		return netState;
	}

	// 个人信息
	@RequestMapping(value = "/getBlanceForSbd", method = RequestMethod.POST)
	public @ResponseBody NetState getBlanceForSbd(HttpServletRequest request, String registration_id) throws Exception {
		NetState netState = new NetState();
		String AuthorizationToken = request.getHeader("SDB-Authorization");
		AcessToken acessToken = null;
		if (AuthorizationToken != null && !AuthorizationToken.equals("")){
			acessToken = TokenUtils.getAcessToken(AuthorizationToken);
		}
		if (acessToken == null) {
			netState.setData("数据签名错误");
			netState.setErrorCode(NetState.SIGN_ERROR);
		} else {
			String Mobile = acessToken.getMobile();
			String ParentId = acessToken.getParentid();
			// 验证参数
			if (Mobile == null || Mobile.equals("") || ParentId == null || ParentId.equals("")) {
				netState.setErrorCode(NetState.PARAMS_ERROR);
				netState.setData("客户端参数错误");
			} else {
				// 查看重复注册
				List<Subscribers> allSub = subscribersService.selectBySub(Mobile, ParentId);
				if (allSub != null && allSub.size() > 1){
					for (Subscribers s : allSub){
						if (s.getShareper() == null || s.getShareper().equals("")){
							subscribersService.deleteByPrimaryKey(s.getId());
						}
					}
				}

				List<Subscribers> subscribers = subscribersService.selectBySub(Mobile, ParentId);
				if (subscribers != null && subscribers.size() > 0) {
					Subscribers us = subscribers.get(0);
					SubscribersResponse sr = new SubscribersResponse();
					us.setCypher(PasswordUtils.decodePWD(us.getPassword()));

					// 绑定极光推送推送id
					try{
						if (registration_id != null){
							List<JpushId> jpushId = jpushIdService.selectByUserID(us.getId());
							if (jpushId == null || jpushId.equals("")){
								jpushIdService.insertSelective(new JpushId(us.getId(), registration_id));
							}
						}
					}catch (Exception e){
						System.out.println("推送id更新失败");
					}

					// 绑定用户邀请码
					List<InviteCode> inviteCode = inviteCodeService.selectByUserID(us.getId());
					if (inviteCode != null && inviteCode.size() > 0){
						us.setInvitecode(inviteCode.get(0).getCode());
					}else{
						String code = us.getId().substring(us.getId().length() - 6);
						us.setInvitecode(code);
						inviteCodeService.insertSelective(new InviteCode(us.getId(), code));
					}

					UsersExample usersExample = new UsersExample();
					usersExample.getOredCriteria()
							.add(usersExample.createCriteria().andIdEqualTo(ParentId).andDatastatusEqualTo(true));
					List<Users> agents = usersService.selectByExample(usersExample);
					if (agents != null && agents.size() == 1) {
						Users agent = agents.get(0);

						if (us.getShopEnddate().contains("CST")) {
							SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
							try {
								Date date = sdf1.parse(us.getShopEnddate());
								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
								String sDate = sdf.format(date);
								us.setShopEnddate(sDate);
							} catch (ParseException e) {
								e.printStackTrace();
							}
						}

						String w = "";
						String time = "";
						String result = VosHelper
								.GetVosAccount("{accounts:['" + agent.getAgentprefix() + us.getMobile() + "']}");
						VosModelList v1 = GsonUtil.getObject(result, VosModelList.class);
						System.out.println(JSONObject.fromObject(v1));
						if (v1.retCode == 0) {
							if (v1.infoCustomers.length > 0) {
								DecimalFormat df = new DecimalFormat("#0.00");
								if (us.getType() == 7) {
									w = df.format(v1.infoCustomers[0].getMoney());
									time = new SimpleDateFormat("yyyy-MM-dd")
											.format(new Date(v1.infoCustomers[0].getValidTime()));
								} else {
									// vos
									int day = Produce.differentDays(new Date(v1.infoCustomers[0].getValidTime()),
											Produce.getNowDate());
									if (us.getType() == 1) {
										w = "" + day + "天/";
									}
									if (us.getType() == 2) {
										w = "" + day + "天/";
									}
									if (us.getType() == 3) {
										w = "" + day + "天/";
									}
									w = df.format(v1.infoCustomers[0].getMoney());
								}
							} else {
								w = "0";
								time = "1970-01-01";
							}
						} else {
							w = "0";
							time = "1970-01-01";
						}
						String[] a = us.getShopEnddate().split(",");
						agent.setIsauth(a.length > 0);
						us.setUsers(agent);
						try{
							us.setBankaccount(userpaysService.selectByUserID(us.getId(), true).getBankno());
							us.setRealname(userpaysService.selectByUserID(us.getId(), true).getBankrealname());
						}catch (Exception e){
							us.setBankaccount("");
							us.setRealname("");
						}
						try{
							us.setAliname(userpaysService.selectByUserID(us.getId(), true).getName());
						}catch (Exception e){
							us.setAliname("");
						}
						// 返回数据
						UserInfoResponse info = voluationUserInfo(request, AuthorizationToken, agent, us, w, time);
						if (!time.equals("")) {
							us.setEndtime(new SimpleDateFormat("yyyy-MM-dd").parse(time));
						}
						subscribersService.updateByPrimaryKeySelective(us);
						netState.setErrorCode(NetState.SUCCESS_CONN);
						netState.setJson(info);
						netState.setData("获取用户信息成功");
						/**
						 *  获取客服的信息
						 */
						Abouts abouts=aboutsService.selectByUserID(ParentId);
						netState.setOtherJson(abouts);
						/**
						 * 每日任务-登录开始
						 */
						// 判断用户是否领取任务
						List<TaskReach> tr = taskReachService.selectByTaskReach(us.getId(), us.getParentid(),
								new SimpleDateFormat("yyyy-MM-dd").format(Parameters.getNowDate()), 1);
						if (tr != null && tr.size() > 0 && tr.get(0).getReceivestatus() == 1 && tr.get(0).getCompletestatus() == 0)
							// 写入用户登录信息
							taskRewardService.insertSelective(
									new TaskReward(us.getParentid(), us.getId(), Produce.getNowDate(), 1));
						/**
						 * 每日任务-登录结束
						 */
					} else {
						netState.setErrorCode(NetState.ACCOUNT_ERROR);
						netState.setData("获取用户信息信息失败");
					}

				} else {
					netState.setErrorCode(NetState.ACCOUNT_ERROR);
					netState.setData("用户不存在");
				}
			}
		}
		Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "查询用户信息");
		apiinfoesService.insert(
				ApiinfoesHelper.setApiinfoes(apiinfoes, AuthorizationToken, GsonUtil.createJsonString(netState)));
		return netState;
	}

	@RequestMapping(value = "/binding", method = RequestMethod.POST)
	public @ResponseBody NetState binding(HttpServletRequest request, String parentId, String mobile, String wxOpenId,
										  String wxName, String wxNumber, String wxPic, String qqOpenId,
										  String qqName, String qqNumber, String qqPic, String appleUserId) {
		NetState netState = new NetState();

		if (parentId == null && parentId.equals("") && mobile == null && mobile.equals("")) {
			netState.setData("参数错误");
			netState.setErrorCode(NetState.PARAMS_ERROR);
		}else {
			List<Subscribers> subscribers = subscribersService.selectBySub(mobile, parentId);
			if (wxOpenId != null && !wxOpenId.equals("")){
				List<Subscribers> wxSubscribers = subscribersService.selectByWxOpenId(wxOpenId,parentId);
				if (wxSubscribers != null && wxSubscribers.size() > 0) {
					netState.setData("该微信已被绑定");
					netState.setErrorCode(NetState.WX_OPENID_REPEAT);
					return netState;
				}
			}

			if (subscribers != null && subscribers.size() > 0){
				Subscribers sub = subscribers.get(0);
				sub.setMobile(mobile);
				sub.setWxopenid(wxOpenId);
				sub.setWxname(wxName);
				sub.setWxnumber(wxNumber);
				sub.setWxpic(wxPic);
//				sub.setQqopenid(qqOpenId);
//				sub.setQqname(qqName);
				sub.setQqnumber(qqNumber);
//				sub.setQqpic(qqPic);
				sub.setPic(wxPic);
				sub.setAppleuserid(appleUserId);
				int code = subscribersService.updateByPrimaryKeySelective(sub);
				if (code == 1){
					netState.setData("绑定成功");
					netState.setErrorCode(NetState.SUCCESS_CONN);
				}else {
					netState.setData("绑定失败");
					netState.setErrorCode(NetState.ERROR_OPERATE);
				}
			}else {
				netState.setData("用户不存在");
				netState.setErrorCode(NetState.NODATA);
			}
		}

		return netState;
	}

	// 微信端 个人信息
	@RequestMapping(value = "/wxGetBlance", method = RequestMethod.POST)
	public @ResponseBody NetState wxGetBlance(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 微信端 跨域请求
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type,Authorization");
		NetState netState = new NetState();
		String AuthorizationToken = request.getHeader("Authorization");
		AcessToken acessToken = TokenUtils.getAcessToken(AuthorizationToken);
		if (acessToken == null || acessToken.equals("")) {
			netState.setData("数据签名错误");
			netState.setErrorCode(NetState.SIGN_ERROR);
		} else {
			String Mobile = acessToken.getMobile();
			String ParentId = acessToken.getParentid();
			// 验证参数
			if (Mobile == null || Mobile.equals("") || ParentId == null || ParentId.equals("")) {
				netState.setErrorCode(NetState.PARAMS_ERROR);
				netState.setData("客户端参数错误");
			} else {
				SubscribersExample subscribersExample = new SubscribersExample();
				subscribersExample.getOredCriteria().add(subscribersExample.createCriteria().andMobileEqualTo(Mobile)
						.andParentidEqualTo(ParentId).andDatastatusEqualTo(true));
				List<Subscribers> subscribers = subscribersService.selectByExample(subscribersExample);
				if (subscribers != null && subscribers.size() > 0) {
					Subscribers us = subscribers.get(0);
					UsersExample usersExample = new UsersExample();
					usersExample.getOredCriteria()
							.add(usersExample.createCriteria().andIdEqualTo(ParentId).andDatastatusEqualTo(true));
					List<Users> agents = usersService.selectByExample(usersExample);
					if (agents != null && agents.size() == 1) {
						Users agent = agents.get(0);
						if (us.getShopEnddate().contains("CST")) {
							SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
							try {
								Date date = sdf1.parse(us.getShopEnddate());
								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
								String sDate = sdf.format(date);
								System.out.println(sDate);
								us.setShopEnddate(sDate);
							} catch (ParseException e) {
								e.printStackTrace();
							}
						}

						String w = "";
						String time = "";
						String result = VosHelper
								.GetVosAccount("{accounts:['" + agent.getAgentprefix() + us.getMobile() + "']}");
						VosModelList v1 = GsonUtil.getObject(result, VosModelList.class);
						if (v1.retCode == 0) {
							if (v1.infoCustomers.length > 0) {
								DecimalFormat df = new DecimalFormat("#0.00");
								if (us.getType() == 7) {
									w = df.format(v1.infoCustomers[0].getMoney());
//									w = v1.infoCustomers[0].getMoney().toString();
									time = new SimpleDateFormat("yyyy-MM-dd")
											.format(new Date(v1.infoCustomers[0].getValidTime()));
								} else {
									// vos
									int day = Produce.differentDays(new Date(v1.infoCustomers[0].getValidTime()),
											Produce.getNowDate());
									if (us.getType() == 1) {
										w = "" + day + "天/";
									}
									if (us.getType() == 2) {
										w = "" + day + "天/";
									}
									if (us.getType() == 3) {
										w = "" + day + "天/";
									}
									w = df.format(v1.infoCustomers[0].getMoney());
//									w = v1.infoCustomers[0].getMoney().toString();
								}
							} else {
								w = "0";
								time = "1970-01-01";
							}
						} else {
							w = "0";
							time = "1970-01-01";
						}
						String[] a = us.getShopEnddate().split(",");
						agent.setIsauth(a.length > 0);
						// 粉丝总数
						us.setLevelAll(rewardsService.countByLevel1And2(us.getId()));
						us.setPic(us.getPic().equals("http://admin.sbdznkj.com/Images/logo.png") ? CommUrls.THISSERVER + "carOwnerService/static/images/sub_logo.png" : us.getPic());
						UserInfo info = new UserInfo();
						info.AndroidVer = agent.getAndroidversion();
						info.AndroidPa = agent.getAndroidpath();
						info.IOSVer = agent.getIosversion();
						info.IOSPa = agent.getIospath();
						info.IsAuth = agent.getIsauth();
						info.Money = w;
						info.Time = time;
						info.Info = us;
						if (!time.equals("")) {
							us.setEndtime(new SimpleDateFormat("yyyy-MM-dd").parse(time));
						}
						subscribersService.updateByPrimaryKeySelective(us);
						netState.setErrorCode(NetState.SUCCESS_CONN);
						netState.setJson(info);
						netState.setData("获取用户信息成功");
					} else {
						netState.setErrorCode(NetState.ACCOUNT_ERROR);
						netState.setData("获取用户信息信息失败");
					}

				} else {
					netState.setErrorCode(NetState.ACCOUNT_ERROR);
					netState.setData("用户不存在");
				}
			}
		}
		Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "查询用户信息");
		apiinfoesService.insert(
				ApiinfoesHelper.setApiinfoes(apiinfoes, AuthorizationToken, GsonUtil.createJsonString(netState)));
		return netState;
	}

	// 详单查询
	@CrossOrigin
	@RequestMapping(value = "/getHD", method = RequestMethod.POST)
	public @ResponseBody NetState getHD(HttpServletRequest request, String Calle164, String SysNum, String Status,
			Integer curPage, String caller, String parentId) throws Exception {
		NetState netState = new NetState();
		String AuthorizationToken = request.getHeader("SDB-Authorization");
		AcessToken acessToken = TokenUtils.getAcessToken(AuthorizationToken);

		if (SysNum != null && SysNum.equals("请输入开始时间") || SysNum != null && SysNum.equals("")){
			SysNum = null;
		}
		if (Status != null && Status.equals("请输入截止时间") || Status != null && Status.equals("")){
			Status = null;
		}

		String Caller = null;
		String ParentID = null;
		// token为空 参数传入
		if (acessToken == null || acessToken.equals("")) {
			Caller = caller;
			ParentID = parentId;
		}else{
			Caller = acessToken.getMobile();
			ParentID = acessToken.getParentid();
		}

		if (Caller == null || ParentID == null) {
			netState.setData("数据签名错误");
			netState.setErrorCode(NetState.SIGN_ERROR);
		} else {
			List<Callbackinfoes> callbackinfoes = null;
			if (curPage != null) {
				// 带分页页码
				CallbackinfoesExamplePage callbackinfoesExample = new CallbackinfoesExamplePage();
				callbackinfoesExample.pagesize = 10;
				callbackinfoesExample.start = (curPage - 1) * callbackinfoesExample.pagesize;
				callbackinfoesExample.rows = callbackinfoesExample.pagesize;// 设置首次分页
				Criteria criteria = callbackinfoesExample.createCriteria();
				callbackinfoesExample.setOrderByClause("CallTime");
				if (Caller == null || ParentID == null) {
					netState.setErrorCode(NetState.PARAMS_ERROR);
					netState.setData("未提交正确参数");
				} else {
					if (!Caller.equals("") && !ParentID.equals("")) {
						criteria.andCallerEqualTo(Caller).andParentidEqualTo(ParentID);
						if (Calle164 != null && !Calle164.equals("")) {
							criteria.andCalle164EqualTo(Calle164);
						}
						if (SysNum != null && !SysNum.equals("") && Status != null && !Status.equals("")) {
							criteria.andCalltimeBetween(
									new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(SysNum + " 00:00:00"),
									new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(Status + " 23:59:59"));
						}
					}
					callbackinfoesExample.getOredCriteria().add(criteria);
					callbackinfoes = callbackinfoesService.selectByExamplePage(callbackinfoesExample);
				}
			} else {
				// 不带 分页页码
				CallbackinfoesExample callbackinfoesExample = new CallbackinfoesExample();
				Criteria criteria = callbackinfoesExample.createCriteria();
				callbackinfoesExample.setOrderByClause("CallTime DESC");
				if (Caller == null || ParentID == null) {
					netState.setErrorCode(NetState.PARAMS_ERROR);
					netState.setData("未提交正确参数");
				} else {
					if (!Caller.equals("") && !ParentID.equals("")) {
						criteria.andCallerEqualTo(Caller).andParentidEqualTo(ParentID);
						if (Calle164 != null && !Calle164.equals("")) {
							criteria.andCalle164EqualTo(Calle164);
						}
						if (SysNum != null && !SysNum.equals("") && Status != null && !Status.equals("")) {
							criteria.andCalltimeBetween(
									new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(SysNum + " 00:00:00"),
									new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(Status + " 23:59:59"));
						}
					}
					callbackinfoesExample.getOredCriteria().add(criteria);
					callbackinfoes = callbackinfoesService.selectByExample(callbackinfoesExample);
				}
			}
			if (callbackinfoes != null && callbackinfoes.size() > 0) {
				netState.setErrorCode(NetState.SUCCESS_CONN);
				netState.setJson(callbackinfoes);
				netState.setData("话单获取成功");
			} else {
				netState.setErrorCode(NetState.NODATA);
				netState.setData("暂无数据");
			}
		}
		Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "话单查询");
		apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes,
				AuthorizationToken + Produce.parmsToString(Calle164), GsonUtil.createJsonString(netState)));
		return netState;
	}

	// 详单查询
	@RequestMapping(value = "/wxGetHD", method = RequestMethod.POST)
	public @ResponseBody NetState wxGetHD(HttpServletRequest request, HttpServletResponse response,String Calle164,
										  String SysNum, String Status, Integer curPage, String caller,
										  String parentId) throws Exception {
		// 微信端 跨域请求
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type,Authorization");
		NetState netState = new NetState();
		String AuthorizationToken = request.getHeader("Authorization");
		AcessToken acessToken = TokenUtils.getAcessToken(AuthorizationToken);

		if (SysNum.equals("请输入开始时间")){
			SysNum = null;
		}
		if (Status.equals("请输入截止日期")){
			Status = null;
		}

		String Caller = null;
		String ParentID = null;
		// token为空 参数传入
		if (acessToken == null || acessToken.equals("")) {
			Caller = caller;
			ParentID = parentId;
		}else{
			Caller = acessToken.getMobile();
			ParentID = acessToken.getParentid();
		}

		if (Caller == null || ParentID == null) {
			netState.setData("数据签名错误");
			netState.setErrorCode(NetState.SIGN_ERROR);
		} else {
			List<Callbackinfoes> callbackinfoes = null;
			if (curPage != null) {
				// 带分页页码
				CallbackinfoesExamplePage callbackinfoesExample = new CallbackinfoesExamplePage();
				callbackinfoesExample.pagesize = 10;
				callbackinfoesExample.start = (curPage - 1) * callbackinfoesExample.pagesize;
				callbackinfoesExample.rows = callbackinfoesExample.pagesize;// 设置首次分页
				Criteria criteria = callbackinfoesExample.createCriteria();
				callbackinfoesExample.setOrderByClause("CallTime");
				if (Caller == null || ParentID == null) {
					netState.setErrorCode(NetState.PARAMS_ERROR);
					netState.setData("未提交正确参数");
				} else {
					if (!Caller.equals("") && !ParentID.equals("")) {
						criteria.andCallerEqualTo(Caller).andParentidEqualTo(ParentID);
						if (Calle164 != null && !Calle164.equals("")) {
							criteria.andCalle164EqualTo(Calle164);
						}
						if (SysNum != null && !SysNum.equals("") && Status != null && !Status.equals("")) {
							criteria.andCalltimeBetween(
									new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(SysNum + " 00:00:00"),
									new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(Status + " 23:59:59"));
						}
					}
					callbackinfoesExample.getOredCriteria().add(criteria);
					callbackinfoes = callbackinfoesService.selectByExamplePage(callbackinfoesExample);
				}
			} else {
				// 不带 分页页码
				CallbackinfoesExample callbackinfoesExample = new CallbackinfoesExample();
				Criteria criteria = callbackinfoesExample.createCriteria();
				callbackinfoesExample.setOrderByClause("CallTime DESC");
				if (Caller == null || ParentID == null) {
					netState.setErrorCode(NetState.PARAMS_ERROR);
					netState.setData("未提交正确参数");
				} else {
					if (!Caller.equals("") && !ParentID.equals("")) {
						criteria.andCallerEqualTo(Caller).andParentidEqualTo(ParentID);
						if (Calle164 != null && !Calle164.equals("")) {
							criteria.andCalle164EqualTo(Calle164);
						}
						if (SysNum != null && !SysNum.equals("") && Status != null && !Status.equals("")) {
							criteria.andCalltimeBetween(
									new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(SysNum + " 00:00:00"),
									new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(Status + " 23:59:59"));
						}
					}
					callbackinfoesExample.getOredCriteria().add(criteria);
					callbackinfoes = callbackinfoesService.selectByExample(callbackinfoesExample);
				}
			}
			if (callbackinfoes != null && callbackinfoes.size() > 0) {
				netState.setErrorCode(NetState.SUCCESS_CONN);
				netState.setJson(callbackinfoes);
				netState.setData("话单获取成功");
			} else {
				netState.setErrorCode(NetState.NODATA);
				netState.setData("暂无数据");
			}
		}
		Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "话单查询");
		apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes,
				AuthorizationToken + Produce.parmsToString(Calle164), GsonUtil.createJsonString(netState)));
		return netState;
	}

	@CrossOrigin
	@RequestMapping(value = "/updateUser", method = RequestMethod.POST)
	public @ResponseBody NetState updateUser(HttpServletRequest request, String address, String birthday, String email,
			                                 Integer gender, String mobile, String userid, String username, String headImage,
											 String wxName, String wxNumber, String qqNumber) {
		NetState netState = new NetState();
		String AuthorizationToken = request.getHeader("SDB-Authorization");
		AcessToken acessToken = TokenUtils.getAcessToken(AuthorizationToken);
		if (acessToken == null || acessToken.equals("")) {
			netState.setData("数据签名错误");
			netState.setErrorCode(NetState.SIGN_ERROR);
		} else {
			Subscribers user = subscribersService.selectByPrimaryKey(userid);
			if (user == null) {
				netState.setErrorCode(NetState.ACCOUNT_ERROR);
				netState.setData("未找到该用户");
			} else if (user.getDatastatus() == false) {
				netState.setErrorCode(NetState.ACCOUNT_ERROR);
				netState.setData("该用户被禁用");
			} else {
				int flag = 1;
				if (address != null && !address.equals("")) {
					user.setAddress(address);
				} else {
					flag = 0;
				}
				if (birthday != null && !birthday.equals("")) {
					user.setBirthday(birthday);
				} else {
					flag = 0;
				}
				if (email != null && !email.equals("")) {
					user.setEmail(email);
				} else {
					user.setEmail("");
					flag = 0;
				}
				if (gender != null && !gender.equals("")) {
					user.setGender(gender.toString());
				} else {
					flag = 0;
				}
				if (mobile != null && !mobile.equals("")) {
					user.setMobile(mobile);
				} else {
					flag = 0;
				}

				if (username != null && !username.equals("")) {
					user.setUsername(username);
				} else {
					flag = 0;
				}

				if (headImage != null && !headImage.equals("")) {
					user.setPic(headImage);
					user.setWxpic(headImage);
				}

				if (wxName != null && !wxName.equals("")){
					user.setWxname(wxName);
				}

				if (wxNumber != null && !wxNumber.equals("")){
					user.setWxnumber(wxNumber);
				}

				if (qqNumber != null && !qqNumber.equals("")){
					user.setQqnumber(qqNumber);
				}

				int re = subscribersService.updateByPrimaryKeySelective(user);
				if (re == 1) {
					netState.setErrorCode(NetState.SUCCESS_CONN);
					netState.setData("修改用户成功");
					if (flag == 1) {
						/**
						 * 每日任务-完善开始
						 */
						// 判断用户是否领取任务
						List<TaskReach> tr = taskReachService.selectByTaskReach(user.getId(), user.getParentid(),
								new SimpleDateFormat("yyyy-MM-dd").format(Parameters.getNowDate()), 6);
						if (tr != null && tr.size() > 0 && tr.get(0).getReceivestatus() == 1 && tr.get(0).getCompletestatus() == 0)
							// 写入用户登录信息
							taskRewardService.insertSelective(
									new TaskReward(user.getParentid(), user.getId(), Produce.getNowDate(), 6));
						/**
						 * 每日任务-完善结束
						 */
					}
				} else {
					netState.setErrorCode(NetState.SYSTEM_ERROR);
					netState.setData("修改用户失败");
				}
			}
		}
		Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "上传个人资料");
		apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes,
				AuthorizationToken + Produce.parmsToString(address, birthday, email, gender, mobile, userid, username),
				GsonUtil.createJsonString(netState)));
		return netState;
	}

	//专属API
	@CrossOrigin
	@RequestMapping(value = "/getUserAcount", method = RequestMethod.POST)
	public @ResponseBody
	NetState getUserAcount(HttpServletRequest request, @RequestParam String mobile, @RequestParam String parentid) {
		NetState netState = new NetState();
//		List<Subscribers> subscribersList = subscribersService.selectBySub(mobile, parentid);
		Users agent = usersService.selectByPrimaryKey(parentid);
//		if (subscribersList.size() <= 0 || agent == null) {
//			netState.setErrorCode(NetState.ACCOUNT_ERROR);
//			netState.setData("用户不存在");
//		}
//		Subscribers user = subscribersList.get(0);
		Long startTime=System.currentTimeMillis();
		log.warn("[时间戳]"+startTime);
		String result2 = VosHelper.GetVosAccount("{accounts:['" + agent.getAgentprefix() + mobile + "']}");
		log.warn("[时间戳结束查询]"+(System.currentTimeMillis()-startTime));
		VosModelList v2 = GsonUtil.getObject(result2, VosModelList.class);

		BigDecimal balance2 = v2.infoCustomers[0].money; // 用户余额
		netState.setErrorCode(NetState.SUCCESS_CONN);
		netState.setData("成功获取");
		netState.setJson(balance2.setScale(2, RoundingMode.HALF_DOWN));
		return netState;
	}

	// 微信端 上传个人资料
	@RequestMapping(value = "/wxUpdateUser", method = RequestMethod.POST)
	public @ResponseBody NetState wxUpdateUser(HttpServletRequest request, HttpServletResponse response, String address,
			String birthday, String email, Integer gender, String mobile, String userid, String username,
			String headImage) {
		// 微信端 跨域请求
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type,Authorization");
		NetState netState = new NetState();
		String AuthorizationToken = request.getHeader("Authorization");
		AcessToken acessToken = TokenUtils.getAcessToken(AuthorizationToken);
		if (acessToken == null || acessToken.equals("")) {
			netState.setData("数据签名错误");
			netState.setErrorCode(NetState.SIGN_ERROR);
		} else {
			Subscribers user = subscribersService.selectByPrimaryKey(userid);
			if (user == null) {
				netState.setErrorCode(NetState.ACCOUNT_ERROR);
				netState.setData("未找到该用户");
			} else if (user.getDatastatus() == false) {
				netState.setErrorCode(NetState.ACCOUNT_ERROR);
				netState.setData("该用户被禁用");
			} else {
				if (address != null && !address.equals("")) {
					user.setAddress(address);
				}
				if (birthday != null && !birthday.equals("")) {
					user.setBirthday(birthday);
				}
				if (email != null && !email.equals("")) {
					user.setEmail(email);
				} else {
					user.setEmail("");
				}
				if (gender != null && !gender.equals("")) {
					user.setGender(gender.toString());
				}
				if (mobile != null && !mobile.equals("")) {
					user.setMobile(mobile);
				}

				if (username != null && !username.equals("")) {
					user.setUsername(username);
				}

				if (headImage != null && !headImage.equals("")) {
					user.setPic(headImage);
				}
				int re = subscribersService.updateByPrimaryKeySelective(user);
				if (re == 1) {
					netState.setErrorCode(NetState.SUCCESS_CONN);
					netState.setData("修改用户成功");
				} else {
					netState.setErrorCode(NetState.SYSTEM_ERROR);
					netState.setData("修改用户失败");
				}
			}
		}
		Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "上传个人资料");
		apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes,
				AuthorizationToken + Produce.parmsToString(address, birthday, email, gender, mobile, userid, username),
				GsonUtil.createJsonString(netState)));
		return netState;
	}

	// TODO 商家身份认证(该接口作用不明确)
	@RequestMapping(value = "/authAgent", method = RequestMethod.POST)
	public @ResponseBody NetState authAgent(HttpServletRequest request, String Mobile, String Password) {
		NetState netState = new NetState();
		if (Mobile == null || Password == null || Password.equals("") || Mobile.equals("")) {
			netState.setErrorCode(NetState.PARAMS_ERROR);
			netState.setData("请输入账户密码");
		} else {
			Users users = usersService.selectByUsername(Mobile);
			if (users == null || "".equals(Password)) {
				netState.setErrorCode(NetState.API_DISABLE);
				netState.setData("您还不是商家");
			} else {
				// 得到启用状态
				boolean state = users.getDatastatus();
				if (!state) {
					netState.setErrorCode(NetState.ACCOUNT_ERROR);
					netState.setData("您目前正在冻结状态请联系客服");
				} else if (!PasswordUtils.decodePWD(Password, users.getPassword())) {
					netState.setErrorCode(NetState.PARAMS_ERROR);
					netState.setData("您输入的密码不正确");
				} else {
					netState.setErrorCode(NetState.SUCCESS_CONN);
					netState.setData("success");
					netState.setJson("success");
				}
			}
		}
		Apiinfoes apiinfoes = ApiinfoesHelper.createApiinfoes(request, "商家身份认证");
		apiinfoesService.insert(ApiinfoesHelper.setApiinfoes(apiinfoes, Produce.parmsToString(Mobile, Password),
				GsonUtil.createJsonString(netState)));
		return netState;
	}

	@PostMapping("/updateSubscribers")
	@ApiOperation("更新用户资料")
	@CrossOrigin
	@ResponseBody
	public ResponseResult updateSubscribers(@Validated SubscribersParam param){
		subscribersService.update(param);
		return ResponseResultUtils.getResponseResultS("修改成功");
	}

	@PostMapping("/getChildrenAgent")
	@ApiOperation("获取子级代理")
	@ResponseBody
	@ApiImplicitParam(name = "userId",value = "用户id")
	public ResponseResult getChildAgent(@RequestParam String userId,@RequestParam Integer pageNum,@RequestParam Integer pageSize){
		Page<Object> page = PageHelper.startPage(pageNum, pageSize);
		List<ChildrenAgent> list =  subscribersService.getChildrenAgent(userId);
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("total",page.getTotal());
		result.put("rows",list);
		return ResponseResultUtils.getResponseResultS("查询成功",result);
	}

	@PostMapping("/getTeamInfo")
	@ApiOperation("获取团队详情")
	@ResponseBody
	@ApiImplicitParam(name = "userId",value = "用户id")
	public ResponseResult getTeamInfo(@RequestParam String userId,@RequestParam Integer pageNum,@RequestParam Integer pageSize){
		Page<Object> page = PageHelper.startPage(pageNum, pageSize);
		List<ChildrenAgent> list = subscribersService.getChildrenAgent(userId);
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("total",page.getTotal()); // 直推人数
		result.put("rows",list);
		// 此处分页所以要在查一次全部
		result.put("teamNum",subscribersService.getChildrenAgentNum(subscribersService.getChildrenAgent(userId)));// 团队人数
		result.put("teamTotalPrice",subscribersService.getTeamTotalPrice(userId));// 团队总业绩
		result.put("teamPtSuccessNum",subscribersService.getTeamPtSuccessNum(userId));// 团队拼团成功总数
		return ResponseResultUtils.getResponseResultS("查询成功",result);
	}

	@PostMapping("/getCommisionByUserId")
	@ApiOperation("获取个人收益详情")
	@ResponseBody
	@ApiImplicitParam(name = "userId",value = "用户id")
	public ResponseResult getCommisionByUserId(@RequestParam String userId){
		Map<String,BigDecimal> result =  commissionService.getCommission(userId);
		return ResponseResultUtils.getResponseResultS("查询成功",result);
	}

	@PostMapping("/getCommisionDetail")
	@ApiOperation("获取收益详情")
	@ResponseBody
	@ApiImplicitParam(name = "userId",value = "用户id")
	public ResponseResult getCommisionDetail(@RequestParam String userId,@RequestParam Integer pageSize ,@RequestParam Integer pageNum){
		BigDecimal rebit = commissionService.getRebit(userId);
		Page<Object> page = PageHelper.startPage(pageNum, pageSize);
		List<Map<String,Object>> list=  commissionService.getCommisionDetail(userId,rebit);
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("total",page.getTotal());
		result.put("rows",list);
		return ResponseResultUtils.getResponseResultS("查询成功",result);
	}


	public UserInfoResponse voluationUserInfo(HttpServletRequest request, String token, Users agent, Subscribers us, String money, String time){
		UserInfoResponse info = new UserInfoResponse();
		BeanUtils.copyProperties(us, info);
		info.AndroidVer = agent.getAndroidversion();
		info.AndroidPa = agent.getAndroidpath();
		info.IOSVer = agent.getIosversion();
		info.IOSPa = agent.getIospath();
		info.AppStore = agent.getAppstore();
		info.IsAuth = agent.getIsauth();
//		info.Other = "https://umoney.duxiaoman.com/h5/?channel=pinzhuan#/main";
		info.Other = "https://sbd.sbdznkj.com/weblist/#/privacy?type=1";
		info.Money = money;
		info.Time = time;
		info.Token = token;
		try {
			NetState netState = countRewards(request, us.getId());
			if (netState.getErrorCode() == 2000){
				info.Integral = (BigDecimal) netState.getJson();
			}else {
				info.Integral = new BigDecimal(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
			info.Integral = new BigDecimal(0);
		}
		return info;
	}

	public SubscribersResponse voluationSubscribers(Subscribers us){
		SubscribersResponse sr = new SubscribersResponse();
		// 实体类赋值到另一个实体类
		BeanUtils.copyProperties(us, sr);
		return sr;
	}
}
